<!DOCTYPE html>
<html>
<!-- This test should not be upstreamed to WPT because it tests the
  Blink-specific memory cache and uses internals API to do that. -->
<title>Service Worker: Memory Cache</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="resources/test-helpers.js"></script>
<script>
var callback;

function getJSONP(url) {
  var sc = document.createElement('script');
  sc.src = url;
  document.body.appendChild(sc);
  return new Promise(resolve => {
      // This callback function is called by appending a script element.
      callback = function(data) { resolve(data); }
    });
}

promise_test(t => {
  var scope = 'resources/memory-cache-controlled.html';
  var worker = 'resources/memory-cache-worker.js';
  var json_url = 'resources/memory-cache.jsonp';
  var registration;
  var frame;

  return service_worker_unregister_and_register(t, worker, scope)
    .then(r => {
        registration = r;
        return wait_for_state(t, r.installing, 'activated');
      })
    .then(() => { return with_iframe(scope); })
    .then(f => {
        frame = f;

        // Request a json file from controlled page.
        assert_false(
            frame.contentWindow.internals.isLoadingFromMemoryCache(json_url),
            'Cache for controlled page should be empty');
        return frame.contentWindow.getJSONP(json_url);
      })
    .then(result => {
        assert_equals(
          result.src,
          'service worker',
          'Response for controlled page should be served by Service Worker');
        assert_true(
          frame.contentWindow.internals.isLoadingFromMemoryCache(json_url),
          'Response for controlled page should be cached');

        // Request a json file from non-controlled page.
        assert_false(
            internals.isLoadingFromMemoryCache(json_url),
            'Cache for non-controlled page should be empty');
        return getJSONP(json_url);
      })
    .then(result => {
        assert_equals(
          result.src,
          'network',
          'Response for non-controlled page should be served by network');
        assert_true(
          internals.isLoadingFromMemoryCache(json_url),
          'Response for non-controlled page should be cached');

        frame.remove();
        return registration.unregister();
      });
  }, 'Non-controlled page should not use a cache filled by Service Worker');
</script>
